﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LiteExpress.Demo.Business;
using Castle.DynamicProxy;
using Autofac;
using Autofac.Extras.DynamicProxy2;
using Dapper;
using System.Configuration;
using System.Data.Common;
using LiteExpress.Core.DbClient;

namespace LiteExpress.Core.ConsoleDemo
{
    public class CallLogger : IInterceptor
    {
        System.IO.TextWriter _output;

        public CallLogger(System.IO.TextWriter output)
        {
            _output = output;
        }

        public void Intercept(IInvocation invocation)
        {
            _output.WriteLine("Calling method {0} with parameters {1}",
                invocation.Method.Name,
                string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray()));

            invocation.Proceed();

            _output.WriteLine("Done: result was {0}.", invocation.ReturnValue);
        }
    }

    class Program
    {
        static IUserService _userService;

        static void Main(string[] args)
        {
            Initiate();

            _userService = ContainerManager.Container.Resolve<IUserService>();

            //var result = _userService.TestSql();
            var result2 = _userService.TestSqlMap();
            
            Console.ReadLine();
        }

        static void Initiate()
        {   
            #region register types
            ContainerManager.UpdateContainer(builder => {
                builder.RegisterAssemblyTypes(
                System.Reflection.Assembly.Load("LiteExpress.Demo.Data")
                ).Where(t => t.Name.EndsWith("Adapter")).AsImplementedInterfaces()
                .EnableInterfaceInterceptors()//此方法需要引入Autofac.Extras.DynamicProxy2;命名空间
               .InterceptedBy(typeof(CallLogger));//aop拦截

                builder.RegisterAssemblyTypes(
                    System.Reflection.Assembly.Load("LiteExpress.Demo.Business")
                    ).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces();

                builder.Register(c => new CallLogger(Console.Out));
            });            
            #endregion           
        }
    }
}
